package com.wty.cmims.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wty.cmims.pojo.Code;
import com.wty.cmims.pojo.InstitutionMedication;
import com.wty.cmims.pojo.Medication;
import com.wty.cmims.pojo.Orders;
import com.wty.cmims.pojo.ResponseResult;
import com.wty.cmims.service.InstitutionMedicationService;
import com.wty.cmims.service.MedicationService;
import com.wty.cmims.service.OrdersService;
import com.wty.cmims.mapper.OrdersMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author wty
* @description 针对表【orders】的数据库操作Service实现
* @createDate 2024-11-03 16:06:44
*/
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>
    implements OrdersService{
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private MedicationService medicationService;
    @Autowired
    private InstitutionMedicationService institutionMedicationService;
    @Override
    public ResponseResult<Orders> ordersAdd(Orders orders) {
        ResponseResult<Orders> responseResult = new ResponseResult<>();
        boolean save = this.save(orders);
        if(save){
            responseResult.setData(orders);
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("订单信息添加成功");
        } else{
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("订单信息添加失败");
        }
        return responseResult;
    }

    @Override
    @Transactional
    public ResponseResult<Void> ordersStatusUpdate(Integer id) {
        ResponseResult<Void> responseResult = new ResponseResult<>();
        // 如果订单状态为已支付，则不做任何操作
        Orders order =  ordersMapper.selectById(id);
        if (order.getIsPay() == 1){
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("订单状态为已支付，无需更新");
            return responseResult;
        }
        LambdaUpdateWrapper<Orders> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Orders::getId, id).set(Orders::getIsPay, 1);
        // 将“id*num,id*num”中的药品id和药品num提取出来
        String medications = ordersMapper.selectById(id).getMedications();
        String[] split = medications.split(",");
        String[] item;
        boolean updateStock = false;
        for (String s : split) {
            item = s.split("\\*");
            LambdaQueryWrapper<InstitutionMedication> imWrapper = new LambdaQueryWrapper<>();
            imWrapper.eq(InstitutionMedication::getInstitutionId, order.getInstitutionId());
            imWrapper.eq(InstitutionMedication::getMedicationId, item[0]);
            InstitutionMedication im = institutionMedicationService.getOne(imWrapper);
            LambdaUpdateWrapper<InstitutionMedication> imUpdateWrapper = new LambdaUpdateWrapper<>();
            imUpdateWrapper
                    .eq(InstitutionMedication::getInstitutionId, order.getInstitutionId())
                    .eq(InstitutionMedication::getMedicationId, item[0])
                    .set(InstitutionMedication::getStock, im.getStock() - Integer.parseInt(item[1]));
            updateStock = institutionMedicationService.update(imUpdateWrapper);
        }
        boolean update = this.update(wrapper);
        if (update && updateStock){
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("订单状态更新成功");
        } else{
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("订单状态更新失败");
        }
        return responseResult;
    }

    @Override
    public ResponseResult<Map<String, Object>> ordersHistoryRecordFind(Map<String, Object> paramsMap) {
        ResponseResult<Map<String, Object>> responseResult = new ResponseResult<>();
        SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Integer pageSize = (Integer) paramsMap.get("pageSize");
        paramsMap.put("start", ((Integer) paramsMap.get("currentPage") - 1) * pageSize);
        List<Map<String, Object>> orders = ordersMapper.findOrdersRecord(paramsMap);
        Integer total = ordersMapper.findOrdersRecordNum(paramsMap);
        // 将“id*num,id*num”中的药品id和药品num提取出来
        for (Map<String, Object> order : orders) {
            // 取出一条记录中的medication
            String medications = (String) order.get("medications");
            // 分割为若干个“id*num”
            String[] split = medications.split(",");
            String[] item;
            List<Medication> medicationsList = medicationService.list();
            List<String> medicationsArray = new ArrayList<>();
            for (String s : split) {
                // 取出一个“id*num”，分割为id和num
                item = s.split("\\*");
                for (Medication medication : medicationsList) {
                    if (medication.getId().equals(Integer.valueOf(item[0]))) {
                        medicationsArray.add(medication.getName() + "*" + item[1]);
                        break;
                    }
                }
            }
            String medicationsString = String.join(",", medicationsArray);
            order.put("medicationsString", medicationsString);

            // 将日期从2024-10-29T21:30:00转换为2024-10-29 21:30格式
            DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            Object orderTimeObj = order.get("order_time");
            if (orderTimeObj instanceof LocalDateTime) {
                LocalDateTime orderTime = (LocalDateTime) orderTimeObj;
                String formattedTime = dtf.format(orderTime);
                order.put("order_time", formattedTime);
            }
        }
        if (!orders.isEmpty()){
            responseResult.setCode(Code.SUCCESS);
            responseResult.setMessage("查询购药记录成功");
            responseResult.setDatas(orders);
            responseResult.setTotal(total);
            responseResult.setCurrentPage((Integer) paramsMap.get("currentPage"));
        }else {
            responseResult.setCode(Code.ERROR);
            responseResult.setMessage("暂无购药记录");
        }
        return responseResult;
    }
}